module Rubtools
  module Tools
    class Android < Rubtools::Recipe
      register_methods %w(devices remove uninstall)

      # Initialize the Android recipe
      #
      def initialize
        @adb = "adb"
      end

      # Puts the list of available devices
      #
      def devices
        verbose get_devices
      end

      # Remove packages
      #
      def remove package
        uninstall package
      end

      # Uninstall packages
      #
      def uninstall packages 
        devices = get_devices

        if devices.any?
          if devices.size > 1
            verbose "There is more than one device:"
            devices.each_with_index {|device, index| puts "#{index}: #{device}"}
            print "Choose one: "

            answer = STDIN.gets.chomp
            begin
              device = devices[Integer(answer)]
            rescue ArgumentError => e
              error "Error: Not a valid option (" + e.message + ")"
            end
          else
            device = devices.first
          end

          if device
            while packages.size > 0 do
              exec @adb + " -s " + device + " uninstall " + packages.pop
            end
          end
        else
          error "No found devices..."
        end
      end

      private

      # Get the list of available android
      # devices
      #
      def get_devices
        return exec_without_output(@adb + " devices").scan(/\n(.*?)\t/).flatten
      end
    end
  end
end
